package ink.lovejinhu.leetcode;

/**
 * @author jinhu
 * created 2021-07-05 11:21
 */
public class Solution_0005 {
    public static void main(String[] args) {
        Solution_0005 solution_0005 = new Solution_0005();
        String test = "babad";
        System.out.println(solution_0005.longestPalindrome(test));
    }

    /**
     * 给你一个字符串 s，找到 s 中最长的回文子串
     * 字串必须是连续的，子序列不是
     *
     * @param s
     * @return
     */
    public String longestPalindrome(String s) {
        char[] chars = s.toCharArray();
        int max = 0;
        int left = 0;
        int right = 0;
        for (int i = 0; i < chars.length; i++) {
            for (int j = i; j < chars.length; j++) {
                if (this.isHuiWen(chars, i, j)) {
                    if ((j - i + 1) > max) {
                        max = j - i + 1;
                        left = i;
                        right = j;
                    }
                }

            }

        }
        StringBuilder res = new StringBuilder();
        for (int i = left; i <= right; i++) {
            res.append(chars[i]);
        }


        return res.toString();
    }

    /**
     * right-left+1l
     *
     * @param param
     * @param left
     * @param right
     * @return
     */
    public boolean isHuiWen(char[] param, int left, int right) {
        StringBuilder leftToright = new StringBuilder();
        StringBuilder rightToLeft = new StringBuilder();
        for (int i = left; i <= right; i++) {
            leftToright.append(param[i]);
        }
        for (int i = right; i >= left; i--) {
            rightToLeft.append(param[i]);
        }
        return leftToright.toString().equals(rightToLeft.toString());
    }
}
